package edu.utdallas.cs.securechat.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.Timer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import edu.utdallas.cs.securechat.main.Client;
import edu.utdallas.cs.securechat.utils.Logger;

public class ChatPanel extends JPanel implements ListSelectionListener,MouseListener,ActionListener,KeyListener{
	private static final long serialVersionUID = 4474569741521442929L;
	private static JList currentUsers = new JList();
	private static JTabbedPane currentConversations;
	private static JTextField chatBox;
	private JButton jbtsend;
	private ClientFrame main;
	private static Client c = null;
	
	public ChatPanel(final ClientFrame main){
		currentConversations = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
		currentUsers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		//currentUsers.setPreferredSize(new Dimension(80,280));
		currentUsers.setSize(new Dimension(80,280));
		currentUsers.addListSelectionListener(this);
		currentUsers.addMouseListener(this);
		setMain(main);
		c = getMain().getClient();
		
		JPanel chatSend = new JPanel();
		chatSend.setLayout(new BorderLayout());
		chatSend.add(new JLabel("chat:"),BorderLayout.WEST);
		chatBox = new JTextField();
		chatBox.addKeyListener(this);
		chatSend.add(chatBox,BorderLayout.CENTER);
		jbtsend = new JButton("Send");
		jbtsend.setMnemonic(KeyEvent.VK_ENTER);
		jbtsend.addActionListener(this);
		chatSend.add(jbtsend,BorderLayout.EAST);		
		
		setLayout(new BorderLayout());
		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,currentConversations, currentUsers);
		add(splitPane, BorderLayout.CENTER);
		splitPane.setDividerLocation(400);
		splitPane.setDividerSize(3);
		//add(currentConversations, BorderLayout.CENTER);
		//add(currentUsers, BorderLayout.EAST);
		add(chatSend, BorderLayout.SOUTH);

		getMain().addWindowListener(new WindowAdapter() {
	        public void windowClosing(WindowEvent evt) {
	        	c.clientExit();
	        	ActionListener task = new ActionListener(){
	        		public void actionPerformed(ActionEvent e){
	        			if(getMain().isDisplayable()){
	        				getMain().dispose();
	        			}
	        		}
	        	};
	        	Timer timer = new Timer(500, task);
	        	timer.setInitialDelay(2000);
	        	timer.setRepeats(false);
	        	timer.start();
	        }
	    });
	}
	
	public static void createNewTab(String user){
		int index = currentConversations.indexOfTab(user);
		if(index==-1){
			currentConversations.addTab(user, new TextPanel());
			index = currentConversations.indexOfTab(user);
			currentConversations.setTabComponentAt(index, new ButtonTabComponent(currentConversations));
			chatBox.requestFocus();
		}
	}
	
	public static void updateUserList(Vector<String> newUsers){
		Logger.log(Logger.DEBUG, "Users: "+newUsers);
		currentUsers.setListData(newUsers);
	}
	
	public static void recievedMessage(String username,String text){
		createNewTab(username);
		currentConversations.setSelectedIndex(currentConversations.indexOfTab(username));
		((TextPanel)currentConversations.getComponentAt(currentConversations.indexOfTab(username))).addText(username+": "+text);
	}
	
	public void sendMessage(){
		String text = chatBox.getText().trim();
		//System.out.println("Text entered: "+text);
		String user = currentConversations.getTitleAt(currentConversations.getSelectedIndex());
		
		for(int i=0;i<currentUsers.getModel().getSize();i++){
			if(user.equals((String)currentUsers.getModel().getElementAt(i))){
				((TextPanel)currentConversations.getSelectedComponent()).addText(c.getUserName()+": "+text);
				c.messageToUser(user, text);
				chatBox.setText("");
			}
		}
	}
	
	public static void removeUser(String username){
		int index = currentConversations.indexOfTab(username);
		if(index != -1){
			((TextPanel)currentConversations.getComponentAt(currentConversations.indexOfTab(username))).addText(username+" has logged off.");
		}
	}
	
	public static void addUser(String username){
		int index = currentConversations.indexOfTab(username);
		if(index != -1){
			c.requestTicket(username);
			c.connectToUser(username);
			((TextPanel)currentConversations.getComponentAt(currentConversations.indexOfTab(username))).addText(username+" has logged on!");
			createNewTab(username);
			currentConversations.setSelectedIndex(currentConversations.indexOfTab(username));
		}
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		JList source = (JList)e.getSource();
		if(source != currentUsers) {
			return;
		}

		if(e.getClickCount() >= 2) {
			int index = source.locationToIndex(e.getPoint());
			String user = (String)source.getModel().getElementAt(index);
			c.requestTicket(user);
			c.connectToUser(user);
			createNewTab(user);
			currentConversations.setSelectedIndex(currentConversations.indexOfTab(user));
		}		
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton source = (JButton)e.getSource();
		if(source != jbtsend){
			return;
		}
		
		if(e.getActionCommand().equals("Send")){
			if(!chatBox.getText().trim().equals("")){
				sendMessage();
			}
		}
	}
	@Override
	public void mouseEntered(MouseEvent e) {}

	@Override
	public void mouseExited(MouseEvent e) {}

	@Override
	public void mousePressed(MouseEvent e) {}

	@Override
	public void mouseReleased(MouseEvent e) {}

	@Override
	public void valueChanged(ListSelectionEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	@Override
	public void keyTyped(KeyEvent e) {
		if(e.getKeyChar() == '\n'){
			if(!chatBox.getText().trim().equals("")){
				sendMessage();
			}
		}
	}
	
	public ClientFrame getMain() {
		return main;
	}

	public void setMain(ClientFrame main) {
		this.main = main;
	}
}